<?php
/**
 * AJAX Handler for Tags: Add - Add a tag to a project.
 * NOTE: There is some login in here for creating a tag that does not exist in the database.
 * NOTE: If it does exist, it uses the existing tag in the database to link agains the project. Capitalisation is ignored for this purpose.
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false && isset($gVAR['tag']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid()) === true) {
		
		// This is enforced in apache, but just in case!
		$match = preg_match('/^[a-zA-Z0-9_]+$/', $gVAR['tag']);
		if($match === false) {
		    header("HTTP/1.1 400 Bad Request");
		    die($nok_caller);
		}
		
		// Make the string SQL safe
		$tag_safe = strtolower($sql_conx->real_escape_string($gVAR['tag']));
		$query = $sql_conx->query("SELECT `tid` FROM `user_tags` WHERE `tag`='{$tag_safe}';");
		if($query === false) {
		    header("HTTP/1.1 500 Internal Server Error");
		    die($nok_caller);
		} else {
		    $num_rows = $query->num_rows;
		    if($num_rows === 0) {
			$query = $sql_conx->query("INSERT INTO `user_tags` ( `tid` , `creator` , `tag` ) VALUES ( NULL ,  '{$_LOGGEDINUSER->get_userid()}',  '{$tag_safe}' )");
			if($query === false) {
			    header("HTTP/1.1 500 Internal Server Error");
			    die($nok_caller);
			} else {
			    $query = $sql_conx->query("SELECT `tid` FROM `user_tags` WHERE `tag`='{$tag_safe}';");
			    if($query === false) {
				header("HTTP/1.1 500 Internal Server Error");
				die($nok_caller);
			    } else {
				$num_rows = $query->num_rows;
				if($num_rows === 0) {
				    header("HTTP/1.1 500 Internal Server Error");
				    die($nok_caller);
				} else {
				    $row = $query->fetch_row();
				    $tag_id = $row[0];
				}
			    }
			}
		    } else {
			$row = $query->fetch_row();
			$tag_id = $row[0];
		    }
		    $query = $sql_conx->query("SELECT `pid` FROM `tool_tags` WHERE `pid`='{$Project->getID()}' AND `tid`='{$tag_id}'");
		    if($query === false) {
			header("HTTP/1.1 500 Internal Server Error");
			die($nok_caller);
		    } else {
			$numRows = $query->num_rows;
			if($numRows === 0) {
			    $query = $sql_conx->query("INSERT INTO `tool_tags` ( `pid` , `tid` ) VALUES ( '{$Project->getID()}',  '{$tag_id}' )");
			    if($query === false) {
				header("HTTP/1.1 500 Internal Server Error");
				die($nok_caller);
			    } else {
				$Project->updateWrite($_LOGGEDINUSER->get_userid(), ($Project->isMaintainer($_LOGGEDINUSER->get_userid()) === true ? ProjectEditType::AddTag : ProjectEditType::AdminAddTag), array($tag_id));
				header("HTTP/1.1 200 OK");
				$Project->updateTriggered();
				$sendExists = <<<EOEXI
				    <!DOCTYPE html>
					<html>
					    <head><title></title></head>
					    <body>
						<script type="text/javascript">
						    parent.TagsEDJX.TagExists(false);
						    parent.EDJXConfirmer.show_ok();
						</script>
					    </body>
					</html>
EOEXI;
				die(''.$sendExists);
			    }
			} else {
			    header("HTTP/1.1 200 OK");
				$Project->updateTriggered();
				$sendExists = <<<EOEXI
				    <!DOCTYPE html>
					<html>
					    <head><title></title></head>
					    <body>
						<script type="text/javascript">
						    parent.TagsEDJX.TagExists(true);
						    parent.EDJXConfirmer.show_nok();
						</script>
					    </body>
					</html>
EOEXI;
				die(''.$sendExists);
			}
		    }
		    
		}
	    } else {
		throw new InvalidProjectException('');
	    }
	    
	} catch(InvalidProjectException $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die($nok_caller);
	}
    } else {
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
?>
